const PATH = require("path");
const { existsSync, statSync, writeFileSync, appendFileSync, renameSync } = require("fs");

const post = ({ req, config, api }) =>
  new Promise((resolve, reject) => {
    const { md5, filename } = req.query;
    const filepath = PATH.join(config.cacheFilePath, md5);
    const savepath = PATH.join(config.saveFilePath, filename);
    const savefilePath = PATH.join(config.savePath, filename);
    req.on("data", (chunk) => {
      console.log(chunk);
      if (existsSync(filepath)) {
        appendFileSync(filepath, chunk);
      } else {
        writeFileSync(filepath, chunk);
      }
    });
    req.on("end", () => {
      console.log(0);
      api.ApiMkdir(config.saveFilePath);
      renameSync(filepath, savepath);
      resolve(savefilePath);
    });
    req.on("error", err => {
      console.log("上传错误");
      reject(err)
    });
  });
const get = ({ req, config }) => {
  const { md5 } = req.query;
  const filepath = PATH.join(config.cacheFilePath, md5);
  if (existsSync(filepath)) {
    return statSync(filepath).size;
  } else {
    return 0;
  }
}

module.exports = { post, get }

